git_ver    = $(shell git describe --always)
git_rev    = $(shell git rev-parse --short HEAD)
git_tag    = $(shell git describe --tags --abbrev=0)
git_branch = $(shell git rev-parse --abbrev-ref HEAD)

BuildVersion := "$(git_branch)_$(git_ver)"
BuildGoVersion := $(shell go version)
BuildTime := $(shell date '+%Y-%m-%dT%H:%M:%SZ')

# in detached HEAD state
ifeq ($(git_branch), HEAD)
	git_branch = $(shell git show-ref | grep $(shell git show HEAD | sed -n 1p | cut -d " " -f 2) | sed 's|.*/\(.*\)|\1|' | grep -v HEAD | sort | uniq | head -n 1)
	# when git checkout <<tag>>, branch may still be empty
	ifeq ($(git_branch), )
		git_branch := $(git_tag)
	endif
	BuildVersion := $(git_branch)_$(git_rev)
endif

# -ldflag 参数
GOLDFLAGS = -s -w -X 'main.BuildVersion=$(git_ver) $(git_branch)'
GOLDFLAGS += -X 'main.GitCommitInfo=$(git_rev)'
GOLDFLAGS += -X 'main.BuildGoVersion=$(BuildGoVersion)'
GOLDFLAGS += -X 'main.BuildTime=$(BuildTime)'

build:
ifeq ($(OS),Windows_NT)
	set GOOS=windows
	set GOARCH=amd64
	go build -o magic_public.exe
else
	CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o magic_public -ldflags "$(GOLDFLAGS)"
endif


vendor:
	go mod vendor
image:
	docker build . -t magic_public
	docker save magic_public:latest -o magic_public.tar

.PHONY: build
